package com.rs.adminweb.dept.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.web.servlet.ModelAndView;

import com.jaxplat.JaxplatBean;
import com.jaxplat.commons.Row;
import com.jaxplat.delegate.CommonsJaxplatDelegate;
import com.jaxplat.util.StringUtils;
import com.rs.commons.delegate.CommonDelegate;
import com.rs.commons.web.AdminBaseAction;
import com.rs.rsbiz.dept.delegate.DeptDelegate;
import com.rs.rsbiz.dept.entity.DeptEntity;
import com.rs.util.Utils;

public class DeptAction extends AdminBaseAction
{

    private DeptDelegate deptDelegate;

    private CommonDelegate commonDelegate;

    public CommonDelegate getCommonDelegate()
    {
        return commonDelegate;
    }

    public void setCommonDelegate(CommonDelegate commonDelegate)
    {
        this.commonDelegate = commonDelegate;
    }

    public DeptDelegate getDeptDelegate()
    {
        return deptDelegate;
    }

    public void setDeptDelegate(DeptDelegate deptDelegate)
    {
        this.deptDelegate = deptDelegate;
    }

    /**
     * 取科室列表
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView deptList(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        params.put("pageNumber", params.getInt("page") == 0 ? 1 : params.getInt("page"));
        params.put("pageSize", params.getInt("rows") == 0 ? 10 : params.getInt("rows"));
        params.put("pageIndex", params.getInt("pageNumber"));
        // params.put("pageSize", params.getInt("rows"));
        Object[] result = deptDelegate.getSecList(params);
        JSONObject json = new JSONObject();
        json.element("total", (Integer) result[1]);
        json.element("rows", (List) result[0]);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 取医院列表
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView initHospital(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        List hosList = null;
        Row params = this.parseRequestParametersToRow(request);
        if (null != params.getString("city_code"))
        {
            hosList = commonDelegate.getAllHospitalOfCity(params.getString("city_code"));
        }
        else
        {
            hosList = commonDelegate.getAllHospitalList();
        }

        JSONObject obj = new JSONObject();
        obj.put("id", "");
        obj.put("name", "请选择");
        obj.put("selected", true);
        JSONArray array = JSONArray.fromObject(hosList);
        array.add(0, obj);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(array.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 取一级科室列表
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView initParentSec(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        List secList = commonDelegate.getAllSectionList(params);
        JSONObject obj = new JSONObject();
        obj.put("id", "");
        obj.put("name", "请选择");
        obj.put("selected", true);
        JSONArray array = JSONArray.fromObject(secList);
        array.add(0, obj);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(array.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 保存科室信息
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView save(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        DeptEntity entity = (DeptEntity) this.parseRequestParametersToModel(request, DeptEntity.class);
        entity.setHospitalId(params.getLong("hospital_id"));
        entity.setCatId(params.getLong("child_cat_id"));
        JSONObject json = new JSONObject();
        boolean chkResult = chkUnique(entity, json);
        if (chkResult)
        {
            boolean result = deptDelegate.saveRec(entity);
            if (result)
            {
                json.element("flag", "success");
                json.element("msg", "保存成功!");
            }
            else
            {
                json.element("flag", "fail");
                json.element("msg", "保存失败!");
            }
        }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 获取科室详情
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView view(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        DeptEntity entity = deptDelegate.getDetailRec(params);
        Map attrs = new HashMap();
        attrs.put("entity", entity);
        return new ModelAndView("../section/section_view", attrs);
    }

    /**
     * 编辑科室
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView edit(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        DeptEntity entity = deptDelegate.getDetailRec(params);

        JSONObject obj = JSONObject.fromObject(entity);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(obj.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 批量导入科室信息 从上传excel文件，再取文件提取信息导入
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView importData(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        params.put("xsdFilePath", request.getRealPath("upload") + "\\xsd\\section.xsd");
        StringBuffer sb = new StringBuffer();
        // try{
        JSONArray result = deptDelegate.importData(params);
        // }catch(GeneralException e){
        // sb.append("errMsg:"+e.getMessage());
        // }
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(result.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 删除科室信息
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Row params = this.parseRequestParametersToRow(request);
        int result = deptDelegate.deleteRec(params);
        JSONObject json = new JSONObject();
        if (result > 0)
            json.element("msg", "删除成功!");
        else
            json.element("msg", "删除失败!");
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().print(json.toString());
        response.getWriter().flush();
        response.getWriter().close();
        return null;
    }

    /**
     * 唯一性校验
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    private boolean chkUnique(DeptEntity entity, JSONObject obj) throws Exception
    {
        CommonsJaxplatDelegate delegate = (CommonsJaxplatDelegate) JaxplatBean.getBean("commonsJaxplatDelegate");
        String sql = "select count(*) as cnt from t_section s   where s.name=? and s.self_code=? and s.hospital_id=?";
        Row tmpRow = null;
        if (Utils.isNullOrBlank(entity.getId()))
        {
            tmpRow = delegate.findRow(sql, new Object[] { entity.getName(), entity.getSelfCode(), entity.getHospitalId() });

        }
        else
        {
            sql += " and id <>?";
            tmpRow = delegate.findRow(sql, new Object[] { entity.getName(), entity.getSelfCode(), entity.getHospitalId(), entity.getId() });

        }

        if (tmpRow != null && tmpRow.getInt("cnt") > 0)
        {
            obj.put("flag", "fail");
            obj.put("msg", "在相同的医院下存在名称或内部编码重复的科室信息!");
            return false;
        }
        else
        {
            return true;
        }

    }

}
